package cn.edu.buu.news.service.impl;

import cn.edu.buu.news.entity.Task;
import cn.edu.buu.news.mapper.TaskMapper;
import cn.edu.buu.news.service.TaskService;
import cn.edu.buu.news.vo.PageQuery;
import cn.edu.buu.news.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Service
@Transactional
public class TaskServiceImpl implements TaskService {

    @Autowired
    private TaskMapper taskMapper;

    @Override
    public void add(Task task) {
        taskMapper.insert(task);
    }

    @Override
    public void deleteById(Long task_id) {
        taskMapper.deleteById(task_id);
    }

    @Override
    public void update(Task task) {
        taskMapper.update(task);
    }

    @Override
    @Transactional(readOnly = true)
    public Task findById(Long task_id) {
        return taskMapper.selectById(task_id);
    }

    @Override
    @Transactional(readOnly = true)
    public List<Task> findAll() {
        return taskMapper.selectAll();
    }

    @Override
    @Transactional(readOnly = true)
    public PageResult<Task> findByPage(PageQuery query) {
        // 校验page和size，避免负数或0
        int page = query.getPage() < 1 ? 1 : query.getPage();
        int size = query.getSize() < 1 ? 10 : query.getSize();
        int offset = (page - 1) * size;

        List<Task> list = taskMapper.selectByPage(query, offset);
        Long total = taskMapper.selectCount(query);
        return new PageResult<>(list, total);
    }
}